package com.piper.core.exception;

import com.piper.core.RequestDataHolder;
import com.piper.core.ResultData;
import com.piper.core.enums.CoreExceptionEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 全局的的异常拦截器（拦截所有的控制器）（带有@RequestMapping注解的方法上都会拦截）
 */
@ControllerAdvice
@Order(200)
public class DefualtExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 拦截业务异常
     */
    @ResponseBody
    @ExceptionHandler(ServiceException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultData notFount(ServiceException e) {
        logger.error("业务异常！", e);
        RequestDataHolder.remove();
        return ResultData.error(e.getErrorMessage());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultData notFount(Exception e) {
        logger.error("服务器未知异常！", e);
        RequestDataHolder.remove();
        return ResultData.error(CoreExceptionEnum.SERVICE_ERROR);
    }

}
